#!/bin/bash
UPGRADE_WORK_DIR="/tmp/upgradeful/tmp/"
upgrade_config=upgradeful.conf
kernel_version=`uname -r`
os_version="normal"
need_restart=0

function get_os_version()
{
    if [ -f /etc/redhat-release ];then
        version=`cat /etc/redhat-release|grep "CentOS Linux release 8.0"`
        if [ -n "$version" ];then
            os_version="centos8"
        fi

        version=`cat /etc/redhat-release|grep "CentOS release 6."`
        if [ -n "$version" ];then
            os_version="centos6"
        fi
    fi

    if [ -f /etc/oracle-release ];then
        version=`cat /etc/oracle-release|grep "Oracle Linux Server release 6."`
        if [ -n "$version" ];then
            os_version="centos6"
        fi
    fi

    if [ -f /etc/issue ];then
        version=`cat /etc/issue|grep "SUSE Linux Enterprise Server 11"`
        if [ -n "$version" ];then
            os_version="suse11"
        fi
    fi
}

function get_machine_arch()
{

    if [ $(uname -m) = "x86_64" ];then
        machine_arch="x64"
    elif [ $(uname -m) = "aarch64" ];then
        machine_arch="aarch64"
    else
        echo "ERROR：unkown machine arch"
        return 1
    fi
}

get_os_version
get_machine_arch


function get_config_value()
{
    local file_path=$1
    local key=$2
    local value
    value=`grep $key $file_path |grep -v ^#|awk -F '=' '{print $2}' | grep -o "[^ ]\+\( \+[^ ]\+\)*"`
    echo $value
}


function download_curl()
{
    curl --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      curl  -k --connect-timeout 5 $1 -o $2   > /dev/null 2>&1
           if [ $? -eq 0 ]; then
              return 0;
           fi
    fi
    return 1;
}

function download_wget()
{
    wget --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
       wget -t 1 -T 5  --no-check-certificate $1 -O $2   > /dev/null 2>&1
       if [ $? -eq 0 ]; then
          return 0;
       fi
   fi
    return 1;
}

function download_file()
{
    local ret=1
    download_curl $1 $2
    if [ $? -ne 0 ]; then
       download_wget $1 $2
    fi
    if [ $? -eq 0 ]; then
      ret=0
    fi

    return $ret
}


function download_upgradeful_conf_file()
{
    MASTER_ADDR=`get_config_value hostguard_setup_config.conf "MASTER_IP"`
    upgradeful_url=https://$MASTER_ADDR/package/upgrade/linux/agent1.0/hostguard-x86_64/upgradeful.conf

    download_file $upgradeful_url "upgradeful.conf"
    if [ $? -ne 0 ]; then
        return 1
    fi

    sed -i "s/hss-agent.*10180/$MASTER_ADDR/g" upgradeful.conf
    return 0
}

function get_package_info()
{
    local info
    rpm --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        info=`get_config_value $upgrade_config "rpm_"$machine_arch"_"$1`
        echo $info
        return 0
    fi

    dpkg --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        info=`get_config_value $upgrade_config "deb_"$machine_arch"_"$1`
        echo $info
        return 0
    fi

    exit 1
}


function download_agent()
{

	hostguard_package_url=`get_package_info url`
	hostguard_package_name=${hostguard_package_url##*/}

    download_file $hostguard_package_url $hostguard_package_name
    if [ $? -ne 0 ]; then
        return 1
    fi

    return 0
}

patchelf_tool=$UPGRADE_WORK_DIR"patchelf"
function download_dependent_config()
{
    if [ "$os_version" != "centos6" -a "$os_version" != "suse11" ];then
        return 0
    fi
	dependent_lib_url=`get_config_value $upgrade_config "dependent_lib_"$machine_arch"_url"`
	patchelf_tool_url=`get_config_value $upgrade_config "patchelf_tool_"$machine_arch"_url"`
	dependent_lib_name="dependent_lib.tar.gz"
	dependent_lib_dir=$UPGRADE_WORK_DIR"dependent_lib"
    mkdir -p $UPGRADE_WORK_DIR

    # download dependent lib files
    download_file $dependent_lib_url $UPGRADE_WORK_DIR$dependent_lib_name
    if [ $? -ne 0 ]; then
        return 1
    fi
    tar -xvf $UPGRADE_WORK_DIR$dependent_lib_name -C $UPGRADE_WORK_DIR/     > /dev/null 2>&1

    #download patchelf tool
    download_file $patchelf_tool_url $patchelf_tool


    chmod +x $patchelf_tool

    return 0
}

function dependent_config()
{

    if [ "$os_version" != "centos6" -a "$os_version" != "suse11" ];then
        return 0
    fi

    cp -f  $dependent_lib_dir/* /usr/local/hostguard/lib/

    if [ $machine_arch = "x64" ];then
        interpreter_option="ld-linux-x86-64.so.2"
    elif [ $machine_arch = "aarch64" ];then
        interpreter_option="ld-linux-aarch64.so.1"
    fi

    cd /usr/local/hostguard/lib
    find ./ -type f|grep -v "libpthread"|grep -v "ld-linux"|xargs -i  $patchelf_tool --force-rpath --set-rpath /usr/local/hostguard/lib/ {}
    $patchelf_tool --set-interpreter /usr/local/hostguard/lib/$interpreter_option /usr/local/hostguard/lib/libpthread.so.0
    cd -     > /dev/null 2>&1
    cd /usr/local/hostguard/bin
    find ./ -type f|grep -v ".sh"|grep -v "hss"|xargs -i $patchelf_tool --force-rpath --set-rpath /usr/local/hostguard/lib/ {}
    find ./ -type f|grep -v ".sh"|grep -v "hss"|xargs -i $patchelf_tool --set-interpreter /usr/local/hostguard/lib/$interpreter_option {}
    cd -    > /dev/null 2>&1
    # fix upgrade in WORKDIR/sudobin
    cd /usr/local/hostguard/sudobin
    find ./ -type f | grep -v ".sh" | grep -v ".service" | xargs -i $patchelf_tool --force-rpath --set-rpath /usr/local/hostguard/lib/ {}
    find ./ -type f | grep -v ".sh" | grep -v ".service" | xargs -i $patchelf_tool --set-interpreter /usr/local/hostguard/lib/$interpreter_option {}
    cd -    > /dev/null 2>&1
    #disable LD_LIBRARY_PATH in service start script
    sed -i "/export/s/^\(.*\)$/echo \"\"/g" /etc/init.d/hostguard

    need_restart=1
    return 0
}

function install()
{

    rpm --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        rpm -ivh $hostguard_package_name
        if [ $? -ne 0 ]; then
            return 1
        fi
        return 0
    fi

    dpkg --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        dpkg -i $hostguard_package_name
        if [ $? -ne 0 ]; then
            return 1
        fi
        return 0
    fi

    return 1
}

function uninstall()
{

    rpm --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        rpm -e --nodeps hostguard
    fi

    dpkg --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        dpkg -P hostguard
    fi
    if [ $? -ne 0 ]; then
        echo "ERROR：uninstall error ,no rpm or dpkg "
    fi
}


function installer_precheck()
{

    local ret=0
    rpm --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      return 0
    fi

    dpkg --version > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      return 0
    fi

    return 1
}


function get_dir_size()
{
      dir_mem=`du -s $1 |awk -F' ' '{print $1}'`
      if [ $? -ne 0 ];then
          dir_mem=0
      fi
      echo $dir_mem;
      return 0;
}

function get_dir_avail_mem()
{
      available_mem=`df $1 |grep -v Avail |awk -F' ' '{print $4}'`
      echo $available_mem
      return 0;
}

function check_user_local()
{
    local_available_mem=`get_dir_avail_mem  "/usr/local/"`
    if [ $local_available_mem -lt 512000 ];then
        echo  "ERROR：　/usr/local of disk is not enough, local_available_mem=$local_available_mem ,less than  512,000"
        return 1
    fi
    return 0;
}

function check_available_mem()
{
    available_mem=`free -m |grep Mem |awk -F' ' '{print $4}'`
    if [ $available_mem -lt 50 ];then
        echo "ERROR：　memory is not enough  $available_mem  ,less than  50"
        return 1
    fi
    return 0;
}


function check_meta_data() {
    local meta_file_name="meta_data.json"
    download_file "http://169.254.169.254/openstack/latest/meta_data.json" $meta_file_name
    if [ $? -ne 0 ];then
        echo "ERROR：download   meta_data.json  failed."
        return 0;
    fi
    if [ ! -s $meta_file_name ];then
        echo "ERROR：check meta_data.json   failed."
        return 0;
    fi
    return 0

}

function check_hostguard_installed()
{
  if [ -d /usr/local/hostguard ];then
       return 1;
  fi
  return 0;
}

function restart()
{
  if command -v service  &> /dev/null; then
      # 使用 service 命令
      service hostguard restart
  else
      systemctl restart hostguard
  fi
}

function install_precheck()
{

    echo "INFO: download conf"
    download_upgradeful_conf_file
    if [ $? -ne 0 ];then
        return 1
    fi


    echo "INFO: check local"
    check_user_local
    if [ $? -ne 0 ];then
        return 1
    fi

    echo "INFO: check available mem"
    check_available_mem
    if [ $? -ne 0 ];then
        return 1
    fi

    #meta检测失败不退出
    check_meta_data

    echo "INFO: installer precheck"
    installer_precheck
    if [ $? -ne 0 ];then
        return 1
    fi

    echo "INFO: download agent"
    download_agent
    if [ $? -ne 0 ];then
        return 1
    fi

    return 0
}
echo "INFO: precheck"
install_precheck
if [ $? -ne 0 ];then
	exit 1
fi

echo "INFO: check hostguard installed"
check_hostguard_installed
if [ $? -ne 0 ];then
    #备份白名单策略
    if [ -f /usr/local/hostguard/run/whitelist_status.dat ];then
        \cp /usr/local/hostguard/run/whitelist_status.dat /tmp/
    fi
    if [ -f /usr/local/hostguard/run/whitelist_result.dat ];then
        \cp /usr/local/hostguard/run/whitelist_result.dat /tmp/
    fi
    echo "INFO: hostguard is installed ,start uninstall"
    uninstall
    if [ $? -ne 0 ];then
       echo "ERROR:  uninstall failed"
       exit 1
    fi
fi

echo "INFO: install"
install
if [ $? -ne 0 ];then
   exit 1
fi
download_dependent_config
dependent_config
#恢复白名单策略
if [ -f /tmp/whitelist_status.dat ];then
    mv -f  /tmp/whitelist_status.dat /usr/local/hostguard/run/
    need_restart=1
fi
if [ -f /tmp/whitelist_result.dat ];then
    mv -f  /tmp/whitelist_result.dat /usr/local/hostguard/run/
    need_restart=1
fi

if [ $need_restart -eq 1 ];then
    restart
fi

rm -f upgradeful.conf && rm -f hostguard* && rm -f meta_data.json  && rm -rf /tmp/upgradeful


#curl -k -O 'https://hss-agent.cn-east-3.myhuaweicloud.com:10180/package/agent/linux/install/agent_Install.sh' &&
#echo 'MASTER_IP=hss-agent.cn-east-3.myhuaweicloud.com:10180' > hostguard_setup_config.conf &&
#echo 'SLAVE_IP=hss-agent-slave.cn-east-3.myhuaweicloud.com:10180' >> hostguard_setup_config.conf &&
#echo 'ORG_ID=' >> hostguard_setup_config.conf &&
#bash agent_Install.sh && rm -f  agent_Install.sh